package com.screen.screendisplay.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.coal.CoalProdoperOutput;
import com.screen.screendisplay.mapper.coal.CoalProdoperOutputMapper;
import com.screen.screendisplay.service.coal.CoalProdoperOutputService;
import com.screen.screendisplay.vo.coal.CoalOutputVO;
import com.screen.screendisplay.vo.coal.CoalOutputUnitsVO;
import com.screen.screendisplay.vo.coal.CoalOutputTrendVO;
import com.screen.screendisplay.vo.wholeproduct.CoalOutputCompletionVO;
import com.screen.screendisplay.vo.wholeproduct.MonthlyOutputCompletionVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 生产经营煤炭产量表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperOutputServiceImpl extends ServiceImpl<CoalProdoperOutputMapper, CoalProdoperOutput> implements CoalProdoperOutputService {

    @Override
    public CoalOutputVO getCoalOutput(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 获取当前月份
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 创建返回对象
        CoalOutputVO vo = new CoalOutputVO();
        
        // 查询年度数据（year_month_type=0, unit_code='TOTAL'）
        LambdaQueryWrapper<CoalProdoperOutput> annualQuery = new LambdaQueryWrapper<>();
        annualQuery.eq(CoalProdoperOutput::getYear, year)
                   .eq(CoalProdoperOutput::getYearMonthType, false)  // 0表示年度数据
                   .eq(CoalProdoperOutput::getUnitCode, "TOTAL");
        CoalProdoperOutput annualData = this.getOne(annualQuery);
        
        if (annualData != null) {
            // 将吨转换为万吨
            BigDecimal divisor = new BigDecimal("10000");
            
            if (annualData.getAnnualPlan() != null) {
                vo.setAnnualPlan(annualData.getAnnualPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (annualData.getAnnualActual() != null) {
                vo.setAnnualActual(annualData.getAnnualActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (annualData.getAnnualCompletionRate() != null) {
                vo.setAnnualCompletionRate(annualData.getAnnualCompletionRate());
            }
            
            if (annualData.getAnnualYoyRate() != null) {
                vo.setAnnualYoyRate(annualData.getAnnualYoyRate());
            }
        }
        
        // 查询月度数据（year_month_type=1, unit_code='TOTAL', month=当前月）
        LambdaQueryWrapper<CoalProdoperOutput> monthlyQuery = new LambdaQueryWrapper<>();
        monthlyQuery.eq(CoalProdoperOutput::getYear, year)
                    .eq(CoalProdoperOutput::getMonth, currentMonth)
                    .eq(CoalProdoperOutput::getYearMonthType, true)  // 1表示月度数据
                    .eq(CoalProdoperOutput::getUnitCode, "TOTAL");
        CoalProdoperOutput monthlyData = this.getOne(monthlyQuery);
        
        if (monthlyData != null) {
            // 将吨转换为万吨
            BigDecimal divisor = new BigDecimal("10000");
            
            if (monthlyData.getMonthlyPlan() != null) {
                vo.setMonthlyPlan(monthlyData.getMonthlyPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (monthlyData.getMonthlyActual() != null) {
                vo.setMonthlyActual(monthlyData.getMonthlyActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            // 计算月完成率
            if (vo.getMonthlyActual() != null && vo.getMonthlyPlan() != null && vo.getMonthlyPlan().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthlyCompletionRate = vo.getMonthlyActual()
                        .divide(vo.getMonthlyPlan(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                vo.setMonthlyCompletionRate(monthlyCompletionRate.setScale(2, RoundingMode.HALF_UP));
            }
            
            if (monthlyData.getMonthlyYoyRate() != null) {
                vo.setMonthlyYoyRate(monthlyData.getMonthlyYoyRate());
            }
        }
        
        return vo;
    }

    @Override
    public List<CoalOutputUnitsVO> getCoalOutputByUnits(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询各单位年度数据（year_month_type=0, unit_code != 'TOTAL'）
        LambdaQueryWrapper<CoalProdoperOutput> query = new LambdaQueryWrapper<>();
        query.eq(CoalProdoperOutput::getYear, year)
             .eq(CoalProdoperOutput::getYearMonthType, false)  // 0表示年度数据
             .ne(CoalProdoperOutput::getUnitCode, "TOTAL")
             .orderByAsc(CoalProdoperOutput::getUnitCode);
        
        List<CoalProdoperOutput> dataList = this.list(query);
        
        // 转换为VO列表
        List<CoalOutputUnitsVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        for (CoalProdoperOutput data : dataList) {
            CoalOutputUnitsVO vo = new CoalOutputUnitsVO();
            vo.setUnitName(data.getUnitName());
            vo.setUnitCode(data.getUnitCode());
            
            if (data.getAnnualPlan() != null) {
                vo.setAnnualPlan(data.getAnnualPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (data.getAnnualActual() != null) {
                vo.setAnnualActual(data.getAnnualActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public List<CoalOutputTrendVO> getCoalOutputTrend(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        
        // 查询最近5年的年度数据（year_month_type=0, unit_code='TOTAL'）
        // 从currentYear往前推5年
        List<Integer> years = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            years.add(currentYear - i);
        }
        
        LambdaQueryWrapper<CoalProdoperOutput> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperOutput::getYear, years)
             .eq(CoalProdoperOutput::getYearMonthType, false)  // 0表示年度数据
             .eq(CoalProdoperOutput::getUnitCode, "TOTAL")
             .orderByDesc(CoalProdoperOutput::getYear);
        
        List<CoalProdoperOutput> dataList = this.list(query);
        
        // 转换为VO列表
        List<CoalOutputTrendVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        for (CoalProdoperOutput data : dataList) {
            CoalOutputTrendVO vo = new CoalOutputTrendVO();
            vo.setYear(data.getYear());
            
            if (data.getAnnualPlan() != null) {
                vo.setAnnualPlan(data.getAnnualPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (data.getAnnualActual() != null) {
                vo.setAnnualActual(data.getAnnualActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (data.getAnnualCompletionRate() != null) {
                vo.setAnnualCompletionRate(data.getAnnualCompletionRate());
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public CoalOutputCompletionVO getCoalOutputCompletion(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 获取当前月份
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 创建返回对象
        CoalOutputCompletionVO vo = new CoalOutputCompletionVO();
        
        // 查询年度数据（year_month_type=0, unit_code='TOTAL'）
        LambdaQueryWrapper<CoalProdoperOutput> annualQuery = new LambdaQueryWrapper<>();
        annualQuery.eq(CoalProdoperOutput::getYear, year)
                   .eq(CoalProdoperOutput::getYearMonthType, false)  // 0表示年度数据
                   .eq(CoalProdoperOutput::getUnitCode, "TOTAL");
        CoalProdoperOutput annualData = this.getOne(annualQuery);
        
        if (annualData != null) {
            // 将吨转换为万吨
            BigDecimal divisor = new BigDecimal("10000");
            
            if (annualData.getAnnualPlan() != null) {
                vo.setAnnualPlan(annualData.getAnnualPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (annualData.getAnnualActual() != null) {
                vo.setAnnualActual(annualData.getAnnualActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (annualData.getAnnualYoyRate() != null) {
                vo.setAnnualYoyRate(annualData.getAnnualYoyRate());
            }
        }
        
        // 查询月度数据（year_month_type=1, unit_code='TOTAL', month=当前月）
        LambdaQueryWrapper<CoalProdoperOutput> monthlyQuery = new LambdaQueryWrapper<>();
        monthlyQuery.eq(CoalProdoperOutput::getYear, year)
                    .eq(CoalProdoperOutput::getMonth, currentMonth)
                    .eq(CoalProdoperOutput::getYearMonthType, true)  // 1表示月度数据
                    .eq(CoalProdoperOutput::getUnitCode, "TOTAL");
        CoalProdoperOutput monthlyData = this.getOne(monthlyQuery);
        
        if (monthlyData != null) {
            // 将吨转换为万吨
            BigDecimal divisor = new BigDecimal("10000");
            
            if (monthlyData.getMonthlyPlan() != null) {
                vo.setMonthlyPlan(monthlyData.getMonthlyPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (monthlyData.getMonthlyActual() != null) {
                vo.setMonthlyActual(monthlyData.getMonthlyActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (monthlyData.getMonthlyYoyRate() != null) {
                vo.setMonthlyYoyRate(monthlyData.getMonthlyYoyRate());
            }
        }
        
        return vo;
    }

    @Override
    public List<MonthlyOutputCompletionVO> getMonthlyOutputCompletion(Integer year) {
        // 如果year为null，使用当前年月
        LocalDate now = LocalDate.now();
        YearMonth currentYearMonth = YearMonth.from(now);
        
        // 计算最近12个月的起始年月
        YearMonth startYearMonth = currentYearMonth.minusMonths(11);
        
        // 查询最近12个月的月度数据（year_month_type=1, unit_code='TOTAL'）
        LambdaQueryWrapper<CoalProdoperOutput> query = new LambdaQueryWrapper<>();
        query.eq(CoalProdoperOutput::getYearMonthType, true)  // 1表示月度数据
             .eq(CoalProdoperOutput::getUnitCode, "TOTAL")
             .and(wrapper -> {
                 // 构建年月范围查询
                 for (int i = 0; i < 12; i++) {
                     YearMonth ym = startYearMonth.plusMonths(i);
                     if (i == 0) {
                         wrapper.and(w -> w.eq(CoalProdoperOutput::getYear, ym.getYear())
                                          .eq(CoalProdoperOutput::getMonth, ym.getMonthValue()));
                     } else {
                         wrapper.or(w -> w.eq(CoalProdoperOutput::getYear, ym.getYear())
                                         .eq(CoalProdoperOutput::getMonth, ym.getMonthValue()));
                     }
                 }
             })
             .orderByDesc(CoalProdoperOutput::getYear)
             .orderByDesc(CoalProdoperOutput::getMonth);
        
        List<CoalProdoperOutput> dataList = this.list(query);
        
        // 转换为VO列表
        List<MonthlyOutputCompletionVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        for (CoalProdoperOutput data : dataList) {
            MonthlyOutputCompletionVO vo = new MonthlyOutputCompletionVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            
            if (data.getMonthlyPlan() != null) {
                vo.setMonthlyPlan(data.getMonthlyPlan().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (data.getMonthlyActual() != null) {
                vo.setMonthlyActual(data.getMonthlyActual().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            if (data.getMonthlyYoyRate() != null) {
                vo.setMonthlyYoyRate(data.getMonthlyYoyRate());
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

}
